<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>图书列表展示</title>
    <link rel="stylesheet" href="css/bootstrap.min.css" />

    <link rel="stylesheet" href="css/list.css" />
    <script type="text/javascript" src="js/jquery.min.js"></script>
    <script type="text/javascript" src="js/bootstrap.min.js"></script>
    <script src="js/jq-paginator.js"></script>
  </head>

  <body>
    <div class="bookContainer">
      <h2>图书列表展示</h2>
      <div class="navbar-justify-between">
        <div>
          <button
            class="btn btn-outline-info"
            type="button"
            onclick="location.href='book_add.html'"
          >
            添加图书
          </button>
          <button
            class="btn btn-outline-info"
            type="button"
            onclick="batchDelete()"
          >
            批量删除
          </button>
        </div>
      </div>

      <table>
        <thead>
          <tr>
            <td>选择</td>
            <td class="width100">图书ID</td>
            <td>书名</td>
            <td>作者</td>
            <td>数量</td>
            <td>定价</td>
            <td>出版社</td>
            <td>状态</td>
            <td class="width200">操作</td>
          </tr>
        </thead>
        <tbody>
          <!-- 图书数据将通过JavaScript动态填充 -->
        </tbody>
      </table>

      <div class="demo">
        <ul id="pageContainer" class="pagination justify-content-center"></ul>
      </div>

      <script>
        getBookList();
        function getBookList() {
          //获取图书列表，使用Ajax从服务器获取数据，请求路径为/book/getBookListByPage?currentPage=1，其中currentPage为当前页码,currentPage=1变量
          $.ajax({
            url: "/book/getBookListByPage" + location.search, //使用location.search获取当前URL的查询参数
            type: "GET",
            success: function (result) {
              console.log(result);
              //判断是否登录
              if(result == null || result.data == null) {
                alert("请先登录");
                location.href = "login.html"; //跳转到登录页面
                return;
              }
              if (result != null) {
                //获取图书列表信息
                var bookList = result.data.bookInfoList;
                //获取表格的tbody元素
                var tbody = $("table tbody");
                //清空表格内容
                tbody.empty();
                //遍历图书列表，生成表格行
                bookList.forEach(function (book) {
                  var tr = `
                      <tr>
                        <td>
                          <input type="checkbox" name="selectBook" value="${book.id}" class="book-select" />
                        </td>
                        <td>${book.id}</td>
                        <td>${book.bookName}</td>
                        <td>${book.author}</td>
                        <td>${book.count}</td>
                        <td>${book.price}</td>
                        <td>${book.publish}</td>
                        <td>${book.statusCN}</td>
                        <td>
                          <button class="btn btn-outline-info" onclick="location.href='book_update.html?id=${book.id}'">修改</button>
                          <button class="btn btn-outline-danger" onclick="deleteBook(${book.id})">删除</button>
                        </td>
                      </tr>`;
                  //将生成的行添加到tbody中
                  tbody.append(tr);
                  //翻页信息
                  var data = result.data;
                  $("#pageContainer").jqPaginator({
                    totalCounts: data.totalCount, //总记录数
                    pageSize: data.pageRequest.pageSize, //每页的个数
                    visiblePages: 5, //可视页数
                    currentPage: data.pageRequest.currentPage, //当前页码
                    first:
                      '<li class="page-item"><a class="page-link">首页</a></li>',
                    prev: '<li class="page-item"><a class="page-link" href="javascript:void(0);">上一页<\/a><\/li>',
                    next: '<li class="page-item"><a class="page-link" href="javascript:void(0);">下一页<\/a><\/li>',
                    last: '<li class="page-item"><a class="page-link" href="javascript:void(0);">最后一页<\/a><\/li>',
                    page: '<li class="page-item"><a class="page-link" href="javascript:void(0);">{{page}}<\/a><\/li>',
                    //页面初始化和页码点击时都会执行
                    onPageChange: function (page, type) {
                      console.log("第" + page + "页, 类型:" + type);
                      if (type != "init") {
                        //更新URL查询参数
                        location.href = "book_list.html?currentPage=" + page;
                      }
                    },
                  });
                });
              }
            },
            error: function (error) {
                console.log(error);
                if(error.status == 401) {
                  alert("请先登录");
                  location.href = "login.html"; //跳转到登录页面
                  return;
                }
            },
          });
        }
        // 删除图书
        function deleteBook(id) {
          var isDelete = confirm("确认删除?");
          if (isDelete) {
            //删除图书
            $.ajax({
              type: "POST",
              url: "/book/deleteBook",
              data: {
                id: id, //冒号左边对应的是后端Controller方法的参数名，右边是前端传递的值
              }, //将图书ID作为数据发送
              success: function (result) {
                console.log(result);
                if (result == "" || result.code == "SUCCESS") {
                  alert("删除图书成功");
                  /* location.href = "book_list.html"; //跳转到图书列表页面 */
                  // 获取当前页码
                  var params = new URLSearchParams(location.search);
                  var currentPage = params.get("currentPage") || 1;
                  // 重新请求当前页的数据，判断是否还有数据
                  $.ajax({
                    url: "/book/getBookListByPage?currentPage=" + currentPage,
                    type: "GET",
                    success: function (result) {
                        var res = result.data;
                      // 判断当前页是否还有数据
                      if (res.bookInfoList && res.bookInfoList.length > 0) {
                        // 当前页还有数据，刷新当前页
                        location.href =
                          "book_list.html?currentPage=" + currentPage;
                      } else {
                        // 当前页没数据，跳转到第一页
                        location.href = "book_list.html?currentPage=1";
                      }
                    },
                  });
                } else {
                  console.log(result);
                  alert(result.data);
                }
              },
              error: function (error) {
                console.log(error);
                if(error.status == 401 && error != null) {
                  alert("请先登录");
                  location.href = "login.html"; //跳转到登录页面
                  return;
                }
              },
            });
          }
        }

        function batchDelete() {
          var isDelete = confirm("确认批量删除?");
          if (isDelete) {
            //获取复选框的id
            var ids = [];
            $("input:checkbox[name='selectBook']:checked").each(function () {
              ids.push($(this).val());
            });
            console.log(ids);
            //批量删除
            $.ajax({
              type: "POST",
              url: "/book/batchDeleteBook",
              data: {
                bookIds: ids, //将选中的图书ID作为数据发送
              },
              success: function (result) {
                console.log(result);
                if (result == "" || result.code == "SUCCESS") {
                  alert("批量删除图书成功");
                  /* location.href = "book_list.html"; //跳转到图书列表页面 */
                  // 获取当前页码
                  var params = new URLSearchParams(location.search);
                  var currentPage = params.get("currentPage") || 1;
                  // 重新请求当前页的数据，判断是否还有数据
                  $.ajax({
                    url: "/book/getBookListByPage?currentPage=" + currentPage,
                    type: "GET",
                    success: function (result) {
                        var res = result.data;
                      // 判断当前页是否还有数据
                      if (res.bookInfoList && res.bookInfoList.length > 0) {
                        // 当前页还有数据，刷新当前页
                        location.href =
                          "book_list.html?currentPage=" + currentPage;
                      } else {
                        // 当前页没数据，跳转到第一页
                        location.href = "book_list.html?currentPage=1";
                      }
                    },
                  });
                } else {
                  console.log(result);
                  alert(result);
                }
              },
              error: function (error) {
                console.log(error);
                if(error.status == 401 && error != null) {
                  alert("请先登录");
                  location.href = "login.html"; //跳转到登录页面
                  return;
                }
              },
            });
          }
        }
      </script>
    </div>
  </body>
</html>
